var express = require('express');
var router = express.Router();
var fs = require('fs');
var getPixels = require("get-pixels")

const app = express();
app.use(express.urlencoded({ extended: true }))
app.use(express.json());

//上传图片的模板
var multer = require('multer');

/* GET home page. */
router.get('/', function(req, res, next) {
    //res.render('index', { title: 'Express' });
    res.redirect('/html/index.html');
});
/* GET admin page. */
router.get('/admin', function(req, res, next) {
    //res.render('index', { title: 'Express' });
    res.redirect('/html/admin.html');
});
router.get('/alljs', function(req, res) {
    const ignores = ['ol.js', 'jquery-1.11.3.js', 'enter.js', 'ol-ext.js'];
    let components = [];
    const files = fs.readdirSync('./public/javascripts')
    files.forEach(function(item, index) {
        if (ignores.indexOf(item) === -1) {
            let stat = fs.lstatSync("./public/javascripts/" + item)
            if (stat.isFile() === true) {
                components.push(item)
            }
        }
    });
    components.sort();
    res.send(components);
});
router.get('/allicons', function(req, res) {
    let components = [];
    const files = fs.readdirSync('./public/images/icons')
    files.forEach(function(item, index) {
        let stat = fs.lstatSync("./public/images/icons/" + item)
        if (stat.isFile() === true) {
            components.push('/images/icons/' + item)
        }
    });
    res.send(components);
});
router.get('/imgsize', function(req, res) {
    let img = req.query.img;
    let imgPath = "./public/mapimage/" + img;
    getPixels(imgPath, function(err, pixels) {
        if (err) {
            console.log("Bad image path")
            return;
        }
        //console.log("got pixels", pixels.shape.slice())
        res.send(pixels.shape);
    })
});
router.post('/getfeaturesofimg', function(req, res) {
    let img = req.body.img;
    let featureids = JSON.parse(req.body.featureids);
    //console.log(featureids);
    let features = [];
    let dir = './public/data/' + img + '/'
    const files = fs.readdirSync(dir);
    files.forEach(function(item, index) {
        let stat = fs.lstatSync(dir + "/" + item);
        if (stat.isFile() === true) {
            //console.log(item.substr(0, item.indexOf('.')));
            if (featureids.indexOf(item.substr(0, item.indexOf('.'))) > -1) {
                let data = fs.readFileSync(dir + "/" + item, 'utf-8');
                let allpropertiesDir = './public/data/' + img + '/properties';
                let dataProperties = fs.readFileSync((allpropertiesDir + "/" + item).replace('.geojson', '.json'), 'utf-8');

                features.push({
                    type: item.substr(0, item.indexOf('_')),
                    featureid: item.substr(0, item.indexOf('.')),
                    geometry: JSON.parse(data),
                    properties: JSON.parse(dataProperties)
                });
            }
        }
    });
    res.send({
        status: 200,
        msg: 'success',
        features: features
    });
});
router.get('/getallpropsofimg', function(req, res) {
    let img = req.query.img;
    let kw = req.query.kw;
    let types = ['点', '线', '面'];
    let allpropertiesDir = './public/data/' + img + '/properties';

    let features = [];
    const files = fs.readdirSync(allpropertiesDir);
    files.forEach(function(item, index) {
        let stat = fs.lstatSync(allpropertiesDir + "/" + item);
        if (stat.isFile() === true) {
            if (kw != null && kw != undefined && types.indexOf(kw) > -1) {
                let typeKey = 'Point';
                switch (kw) {
                    case '点':
                        typeKey = 'Point';
                        break;
                    case '线':
                        typeKey = 'LineString';
                        break;
                    case '面':
                        typeKey = 'Polygon';
                        break;
                }
                if (item.startsWith(typeKey)) {
                    let data = fs.readFileSync(allpropertiesDir + "/" + item, 'utf-8');
                    features.push(JSON.parse(data));
                }
            } else if (kw != null && kw != undefined) {
                let data = fs.readFileSync(allpropertiesDir + "/" + item, 'utf-8');
                if (data.indexOf(kw) > -1)
                    features.push(JSON.parse(data));
            } else if ((req.query.featureid != undefined && item.startsWith(req.query.featureid)) || req.query.featureid == undefined) {
                let data = fs.readFileSync(allpropertiesDir + "/" + item, 'utf-8');
                features.push(JSON.parse(data));
            }
        }
    });
    res.send({
        status: 200,
        msg: 'success',
        features: features
    });
});
router.post('/savegeometry', function(req, res) {
    let dat = req.body;
    let img = dat.img;
    let id = dat.id;
    let geom = dat.geom;

    let dir = './public/data/' + img + '/';
    // 创建 /tmp/a/apple 目录，无论是否存在 /tmp 和 /tmp/a 目录。
    fs.mkdirSync(dir, { recursive: true });

    let json = JSON.parse(geom);
    let str = JSON.stringify(json, null, '\t');
    fs.writeFile(dir + id + ".geojson", str, function(err) {
        if (err) { res.status(500).send('写入Geometry错误') }
    });
    res.send({
        status: 200,
        msg: 'success',
        id: id
    });
});
//生成的图片放入uploads文件夹下
var uploadicon = multer({ dest: './data/tmp' })
router.post('/uploadicon', uploadicon.single('file'), (req, res) => {
    fs.readFile(req.file.path, (err, data) => {
        //读取失败，说明没有上传成功
        if (err) { return res.send('上传失败') }
        let filePath = '/images/icons/' + req.file.filename + req.file.originalname;
        fs.writeFile('./public' + filePath, data, (err) => {
            if (err) { return res.status(500).send('写入失败'); }
            fs.unlinkSync(req.file.path);
            res.send({ status: 200, msg: 'success', path: filePath });
        })
    })
});
router.post('/uploadfeatureimage', uploadicon.single('file'), (req, res) => {
    //console.log(req.file);
    fs.readFile(req.file.path, (err, data) => {
        if (err) { return res.send('上传失败') }
        let featureid = req.body.featureid;
        let dir = '/data/' + req.body.img + '/images' + '/' + featureid;
        let filePath = dir + "/" + req.file.filename + req.file.originalname;
        fs.mkdirSync('./public' + dir, { recursive: true });
        fs.writeFile('./public' + filePath, data, (err) => {
            if (err) { return res.status(500).send('写入失败'); }
            fs.unlinkSync(req.file.path);
            res.send({ status: 200, msg: 'success', path: filePath });
        })
    })
});

router.post('/saveproperties', function(req, res) {
    let json = JSON.parse(req.body.properties);
    let featureid = json.featureid;
    let img = json.img;
    let dir = '/data/' + img + '/properties/';
    let filePath = dir + "/" + featureid + ".json";
    fs.mkdirSync('./public' + dir, { recursive: true });
    let str = JSON.stringify(json, null, '\t');
    fs.writeFile('./public' + filePath, str, function(err) {
        if (err) { res.status(500).send('saveproperties写入错误') }
    });
    res.send({
        status: 200,
        msg: 'success',
        img: img,
        id: featureid
    });
});
module.exports = router;